<?php
/***************************************************************************
 *   copyright : (C) 2009 Udrea Cristian
 *   site : http://code.google.com/p/testauction-php
 ***************************************************************************/

/***************************************************************************
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as 
 *   published by the Free Software Foundation; either version 2 of the
 *   License, or (at your option) any later version. Although none of the
 *   code may be sold. If you have been sold this script, get a refund.
 ***************************************************************************/
include("../include/database.php");
include("../include/classes/class.AuctionHandler.php");

$hour = date('H', time());
$closed = ($hour >= OPENING_HOUR && $hour < CLOSING_HOUR) ? false : true;
if(!$closed) {
	$result = $auctionDB->getOpenAuctions();
	foreach($result as $auction) {
		// has it started?
		if(!$auction['closed'] && $auction['starts_timestamp'] < time()) {
			//decrement time_left
			if($auction['new_bid']){
				$auction['time_left'] = $auction['time_interval'];
				execute_update('UPDATE ' . TBL_AUCTIONS . ' SET time_left = ?, new_bid = ? WHERE auction_id = ?', 
					array($auction['time_left'], 0, $auction['auction_id']));
			}
			elseif($auction['time_left'] > 0) {
				/*$auction['time_left'] --;
				execute_update('UPDATE ' . TBL_AUCTIONS . ' SET time_left = ? WHERE auction_id = ?', 
				array($auction['time_left'], $auction['auction_id']));	
				}*/
				$last_offer = $auctionDB->getAuctionLatestOffer($auction['auction_id']);
				$timestamp = ($auctionDB->getAuctionOfferCount($auction['auction_id']) > 0) ? $last_offer['timestamp'] : $auction['starts_timestamp'];
				echo time()-$timestamp;
				$auction['time_left'] = $auction['time_interval'] - (time()-$timestamp);
				execute_update('UPDATE ' . TBL_AUCTIONS . ' SET time_left = ? WHERE auction_id = ?', 
					array($auction['time_left'], $auction['auction_id']));
			}
			else {
				//Auction over. Close it and declare winner.
				execute_update('UPDATE '. TBL_AUCTIONS .' SET closed = ?, closed_timestamp = ? WHERE auction_id = ?', array(1, time(), $auction['auction_id']));
				//Create the order in the table
				if($auctionDB->getAuctionOfferCount($auction['auction_id']) > 0) {
					$last_offer = $auctionDB->getAuctionLatestOffer($auction['auction_id']);
					$userkey = $last_offer['userkey'];
					$sql = "INSERT INTO ". TBL_ORDERS ." (auction_id, od_date, od_last_update, od_shipping_userkey) VALUES (?, NOW(), NOW(), '$userkey')";
					execute_update($sql, array($auction['auction_id']));
				}
			}
		}
	}
}
?>
